package org.tc.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.tc.result.PicUploadResult;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by zxd on 2018/1/26.
 */
@Controller
@RequestMapping("/pic")
public class UploadController {


    private Logger LOGGER= LoggerFactory.getLogger(UploadController.class);

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public PicUploadResult upload(@RequestParam  MultipartFile uploadFile, HttpServletRequest request) throws IOException {
        //上传图片的路径
        String path="E://image";

        //获取文件后缀
        String filename = uploadFile.getOriginalFilename();
        String end=filename.substring(filename.lastIndexOf("."));

        LOGGER.debug("filename is {}.,end is {}",filename,end);
        //新的文件名
        String uuid_name= UUID.randomUUID().toString()+end;

        LOGGER.debug("uuid_name is {},",uuid_name);

        File file =new File(path+ File.separator+uuid_name);

        //保存图片到磁盘
        uploadFile.transferTo(file);

        //封装结果集对象，返回响应的json数据
        PicUploadResult picUploadResult=new PicUploadResult();
        //上传成功的状态
        picUploadResult.setError(0);
        //设置路径
        picUploadResult.setUrl("http://image.yufan.com/"+uuid_name);

        //获取宽和高
        BufferedImage image= ImageIO.read(file);
        if(image!=null){
            picUploadResult.setWidth(image.getWidth()+"");
            picUploadResult.setHeight(image.getHeight()+"");
            LOGGER.info("上传成功! 上传的文件名称是 {},上传文件的地址{}",file.getName(),file.getPath());
        }else{
            //上传失败
            picUploadResult.setError(1);
            LOGGER.error("上传文件失败! 上传者的ip地址:{},上传的文件名称是 {}",request.getRemoteAddr(),filename);
        }
        return picUploadResult;
    }


}
